// 初始化地图
loadGoogleMap();
//loadMarker();

var Map = Class.create();
Map.prototype.initialize = function(mapid,opts){
	opts = opts || {};
	this.mapElement = mapid;
	this.smallType = opts.smallType || false;
	this.zoom = opts.zoom || 13;
	this.LabelName = opts.labelName || '地图房源列表';
	this.requestUrl = opts.requestUrl || '/aspx/xmlhttp.aspx';
	
	this.latlng  = (opts.latlng)?this.getGLatLng(opts.latlng):this.getGLatLng('24.4880, 118.1859');
	this.initMap();
}

Map.prototype.initMap= function(){
	if (GBrowserIsCompatible()){
		this.M = new GMap2($(this.mapElement));
		var mapui = this.M.getDefaultUI();
		mapui.maptypes.physical = false;
		this.M.setUI(mapui);
		this.M.disableDoubleClickZoom();
        this.M.enableScrollWheelZoom();
		if(!this.smallType){
        	this.M.addControl(new GMapTypeControl()); 
		}
		this.G = new GClientGeocoder();
		this.M.setCenter(this.latlng,this.zoom);
		GEvent.addListener(this.M, 'zoomend', function(){this.zoom = this.M.getZoom()}.bind(this)); 
		GEvent.addListener(window, 'unload', GUnload); 
		return this.M;
	}else{
		alert('您的浏览器不支持地图模式！');
		return;
	}
}

Map.prototype.getGLatLng = function(strLatLng){
	return new GLatLng(strLatLng.split(',')[0], strLatLng.split(',')[1]);
}
Map.prototype.setCenter = function(latlng,zoom){
	this.latlng = this.getGLatLng(latlng);
	this.zoom = zoom;
	this.M.setCenter(this.latlng,zoom);
}

Map.prototype.addMarker = function(strLatlng,markOpts){
	if(strLatlng.indexOf(',')>=0){
		markOpts = markOpts || {};
		var oLatLng = this.getGLatLng(strLatlng);
		var marker = new GMarker(oLatLng, markOpts);
		this.M.addOverlay(marker);
		this.M.setCenter(oLatLng,markOpts.zoom);
		if(markOpts.title!=null&&markOpts.title!=''){
			marker.openInfoWindowHtml((markOpts.title||'位置所在'));
		}
		return marker
	}
	return ;
}
Map.prototype.createFindcontrol = function(){
	var findControl = Class.create();
	findControl.prototype = new GControl();
	findControl.prototype.initialize = function(map){
		var container = map.getContainer();
		var label = document.createElement("div");
		container.appendChild(label);
		label.innerHTML = "Hello World";
		return label;
	}
	
	findControl.prototype.getDefaultPosition = function(){
		return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(50, 10));
	}
	this.M.addControl(new findControl()); 
}
Map.prototype.enableFindAddress = function(){
	findControl = Class.create();
	findControl.prototype = new GControl();
	findControl.prototype.initialize = function(map){
		var container = document.createElement("div");
		Element.setStyle(container,{backgroundColor:'#fff',padding:'2px 4px 2px 4px',fontSize:'12px',border:'1px solid #ccc'});
		var input = document.createElement("input");
		input.type='text';
		Element.setStyle(input,{fontSize:'12px'});
		Event.observe(input,'keydown',function(item){
											   var code = (Prototype.Browser.IE)?event.keyCode:event.which;
											   if(code==13){
												   this.find(item.value);
											   };
											   return false;
											}.bind(this,input));
		container.appendChild(input);
		this.findControlInput = input;
		
		var button = document.createElement("input");
		button.type='button';
		button.value = '定位'
		Element.setStyle(button,{fontSize:'12px'});
		Event.observe(button,'click',function(item){this.find(item.value);}.bind(this,input));
		
		container.appendChild(button);
	
		map.getContainer().appendChild(container);
		return container;
	}.bind(this);
	findControl.prototype.getDefaultPosition = function(){
		return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100, 5));
	}
	this.M.addControl(new findControl(this.M)); 
}
Map.prototype.setSmallMap = function(){
	this.M.addControl(new GSmallMapControl());
	this.M.addControl(GSmallZoomControl);
}
Map.prototype.setFindControlValue = function(value){
	this.findControlInput.value  = value;
}
Map.prototype.addDragMarker = function(objid,markOpts){
	if(typeof(objid)!='function'){
		var objid=Object.isString(objid)?$(objid):objid; 
		if(objid==null){
			alert('对象['+objid+']不存在');
			return;
		}else if(objid.value.indexOf(',')>=0){
			this.latlng = this.getGLatLng(objid.value);
		}
	}
	markOpts = markOpts || {} ;
	markOpts.draggable = true;
    this.dragMarker = new GMarker(this.latlng, markOpts);
    GEvent.addListener(this.dragMarker, "dragstart", function() {
        this.M.closeInfoWindow();
    }.bind(this));

    GEvent.addListener(this.dragMarker, "dragend", function(title,objid) {
        this.latlng = this.dragMarker.getLatLng();
		this.dragMarker.openInfoWindowHtml((title||'移动至此位置'));
		if(typeof(objid)!='function'){
			if(objid.tagName.toUpperCase()=='INPUT'){
				objid.value = this.getLatlngValue();
			}else{
				objid.innerHTML = this.getLatlngValue();
			}
		}else{
			objid(this.latlng);
		}
    }.bind(this,markOpts.title,objid));
    this.M.addOverlay(this.dragMarker);
	this.M.setCenter(this.latlng,this.zoom);
}

Map.prototype.getLatlngValue = function(){
	return this.latlng.lat() +','+this.latlng.lng();
}

/*自定义地图标识*/
Map.prototype.getCustomIcon = function(IconOptions){ 
	var myIcon = new GIcon(G_DEFAULT_ICON), i; 
	for (i in IconOptions) { 
		switch (i) { 
			case 'iconSize': 
			case 'shadowSize': 
			case 'dragCrossSize': 
				myIcon[i] = new GSize(IconOptions[i][0], IconOptions[i][1]); 
				break; 
			case 'iconAnchor': 
			case 'infoWindowAnchor': 
			case 'infoShadowAnchor': 
			case 'dragCrossAnchor': 
				myIcon.iconAnchor = new GPoint(IconOptions[i][0], IconOptions[i][1]); 
				break; 
			default: 
				myIcon[i] = IconOptions[i]; 
				break; 
		} 
	} 
	return myIcon; 
}
Map.prototype.find = function(address){
    this.G.getLatLng(
    address,
    function(point) {
        if (!point) {
            alert('地址:'+ address + " 没有找到！！");
        } else {
            this.M.setCenter(point, this.zoom);
			if(this.dragMarker!=null){
            	this.dragMarker.setPoint(point);
				this.dragMarker.openInfoWindowHtml(address);
			}
        }
    }.bind(this)
  )
}

/**地图随移找房**/
Map.prototype.enableMovedFind = function(){
	GEvent.addListener(this.M, "moveend", function() {
												   this.loadMapXml();
												   }.bind(this));
}
Map.prototype.query = function(query){
	this.query = 'f='+encodeURI(this.LabelName)+((query)?('&'+query):'');
	this.loadMapXml();
}
Map.prototype.getBoundsQuery= function(){
	var a  = this.M.getBounds();
	var bounds = {minLat:a.getSouthWest().lat()
					,minLng : a.getSouthWest().lng()
					,maxLat : a.getNorthEast().lat()
					,maxLng : a.getNorthEast().lng()}
	return '&minLat='+bounds.minLat+'&minLng='+bounds.minLng+'&maxLat='+bounds.maxLat+'&maxLng='+bounds.maxLng;
}

Map.prototype.loadMapXml = function(){
	param = this.query+this.getBoundsQuery();
	GDownloadUrl("/aspx/xmlhttp.aspx?"+param, function(data, responseCode) {
			if(responseCode==200){
			this.M.clearOverlays();
			var xml = GXml.parse(data);
			var marker = null;
			if(xml==null||xml.documentElement==null) return;
			var markers = xml.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++) {
				var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
										parseFloat(markers[i].getAttribute("lng")));
				var title = markers[i].getAttribute("title");
				var usertype = markers[i].getAttribute("usertype");
				/*marker = new mMarker(point,title,{className:((usertype==2)?'marker':'marker1')});
				this.M.addOverlay(marker);*/
				//marker.openInfoWindowHtml(title);
				this.M.addOverlay(new GMarker(point));
				//marker = new GMarker(point,icon)
/*				marker.openInfoWindowHtml(infoTabs);
				marker.openInfoWindow('ssssssssssssss');*/
				//marker.openInfoWindowTabsHtml(infoTabs);
				//map.addOverlay(createMarker(point,i));
				}
			}
		}.bind(this));
}

Map.prototype.loadMapMarker = function(){
	function mMarker(point ,title, opt_MarkerOptions) {
		
		opt_MarkerOptions = (opt_MarkerOptions==null)?{}:opt_MarkerOptions;
		this.point_ = point;
		this.title_ = title;
		this.color_ = opt_MarkerOptions.color || "#ffffff";
		this.className_ = opt_MarkerOptions.className|| 'marker';
	}
	

	
	// Creates the DIV representing this rectangle.
	mMarker.prototype.initialize = function(map) {
	  // Create the DIV representing our rectangle
	  var div = document.createElement("div");
	  div.className = this.className_;
	  div.style.position = "absolute";
	  div.style.color = this.color_;
	  div.style.whiteSpace='nowrap';
	  div.style.width = (this.title_.length*12+20) + 'px';
	  div.style.zIndex = maxzIndex++;
	  div.style.cursor ='default';
	  div.point_ = this.point_;
	  div.innerHTML =  '<div class="markersilder"><div class="markercontent">'+this.title_.substring(0,20)+'</div></div>';
	  
	  GEvent.addDomListener(div, "mouseover", function() {
		div.style.zIndex = maxzIndex++;
	  });
	  GEvent.addDomListener(div, "click", function() {
		map.openInfoWindowHtml(div.point_,'00000000000000');
	  });
	  // Our rectangle is flat against the map, so we add our selves to the
	  // MAP_PANE pane, which is at the same z-index as the map itself (i.e.,
	  // below the marker shadows)
	  
	  map.getPane(G_MAP_MAP_PANE).appendChild(div);
	  this.map_ = map;
	  this.div_ = div;
	}
	
	// Remove the main DIV from the map pane
	mMarker.prototype.remove = function() {
	  this.div_.parentNode.removeChild(this.div_);
	}
	
	// Copy our data to a new Rectangle
	mMarker.prototype.copy = function() {
	  return new mMarker(this.point_, this.weight_, this.color_);
	}
	
	// Redraw the rectangle based on the current projection and zoom level
	mMarker.prototype.redraw = function(force) {
	  // We only need to redraw if the coordinate system has changed
	  if (!force) return;
	
	  var c = this.map_.fromLatLngToDivPixel(this.point_);
	  this.div_.style.left = c.x+"px";
	  this.div_.style.top = c.y-this.div_.offsetHeight+"px";
	}
	mMarker.prototype = Object.extend(new GOverlay(),{
												   
												   });
}
function getGoogleMapKey(){
	var mapKeys = {},i;
	mapKeys['xmhouse.org'] = 'ABQIAAAAp0ssKXEZ7ZL_GN9NUALG9RS3WF-SzLv5RGfZ72sb2dmT1B3fhxTA4xuwcv_pUugDpIsCcd-qBQ-Oew'
	mapKeys['localhost'] = 'ABQIAAAAp0ssKXEZ7ZL_GN9NUALG9RT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTtGSPONaesvuOrDn1qK_YtVD63mw'
	mapKeys['xmhouse.com'] = 'ABQIAAAAp0ssKXEZ7ZL_GN9NUALG9RQitP7lxcmrjVD-eTGYRMAHYzMQkhQIRN0uiG3t5uGmm_78nyltnnpkbg'
	for(i in mapKeys){
		if(location.hostname.indexOf(i)>1){
			return mapKeys[i];
		}
	}
}
function loadGoogleMap() {
	var mapKey = getGoogleMapKey();
	var src = 'http://ditu.google.cn/maps?file=api&amp;v=2&amp;key='+mapKey+'&hl=zh-CN';
    try{
      // inserting via DOM fails in Safari 2.0, so brute force approach
      document.write('<script type="text/javascript" src="'+src+'"><\/script>');
	  document.domain;
	  
    } catch(e) {
      // for xhtml+xml served content, fall back to DOM methods
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = src;
      document.getElementsByTagName('head')[0].appendChild(script);
    }
}
